<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="知识库名称" prop="wikiNames">
              <el-input v-model="queryParams.wikiNames" placeholder="请输入知识库名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="成员" prop="userName">
              <el-input v-model="queryParams.userName" placeholder="请输入成员名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['know:wikiApps:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
              <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                v-hasPermi="['know:wikiApps:edit']">修改</el-button>
            </el-col> -->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['know:wikiApps:remove']"
              >删除</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
              <el-button type="warning" plain icon="Download" @click="handleExport"
                v-hasPermi="['know:wikiApps:export']">导出</el-button>
            </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <!-- 表格数据 -->
      <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="id" v-if="false" />

        <el-table-column label="知识库名称" align="center">
          <template #default="scope">
            <div v-if="scope.row.wikiNames">
              <span v-for="(item, index) in scope.row.wikiNames.split(',')" :key="index" class="tag_class"> {{ item }}</span>
              <!-- <el-tag v-for="(item, index) in scope.row.wikiNames.split(',')" :key="index" class="tag_class">
                {{ item }}
              </el-tag> -->
            </div>
          </template>
        </el-table-column>

        <!-- <el-table-column label="应用名称" align="center" prop="appName" /> -->
        <el-table-column label="秘钥" align="center" prop="appKey" />
        <el-table-column label="知识库ID" align="center" prop="wikiIds" />
        <el-table-column label="成员" align="center" prop="userName" />
        <el-table-column label="是否公开" align="center" prop="open">
          <template #default="scope">
            <span class="tag_class">
              {{ scope.row.open === 1 ? '公开' : '不公开' }}
            </span>
          </template>
        </el-table-column>

        <!-- <el-table-column label="应用类型" align="center" prop="wikiType">
          <template #default="scope">
            {{ getDictDataLabel(scope.row.wikiType) }}
          </template>
        </el-table-column> -->

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['know:wikiApps:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['know:wikiApps:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="配置" placement="top">
              <el-button link type="primary" icon="Setting" @click="configure(scope.row)" v-hasPermi="['know:wikiApps:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="权限" placement="top">
              <el-button link type="primary" icon="UserFilled" @click="openRoleDialog(scope.row)" v-hasPermi="['know:wikiApps:edit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改知识库配置对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="dialogFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="应用名称" prop="wikiNames">
          <el-input v-model="form.wikiNames" placeholder="请输入应用名称" />
        </el-form-item>

        <el-form-item label="是否公开" prop="open">
          <el-select v-model="form.open" placeholder="请选择是否公开" style="width: 338px">
            <el-option v-for="item in openType" :key="item.val" :label="item.label" :value="item.val" />
          </el-select>
        </el-form-item>

        <el-form-item label="秘钥" prop="appKey" v-if="!isappKey">
          <el-input v-model="form.appKey" placeholder="请输入秘钥" />
        </el-form-item>
        <!-- <el-form-item label="应用类型" prop="wikiType">
          <el-select v-model="form.wikiType" placeholder="请选择应用类型" style="width: 338px">
            <el-option v-for="item in wiki_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="关联知识库" prop="wikiIds">
          <el-button type="primary" icon="Plus" plain @click="handleSelectWiki">关联知识库</el-button>
          <div>
            <el-tag v-for="(item, index) in wikiList" :key="index" class="tag_class">{{ item.name }}</el-tag>
          </div>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 配置弹框 -->
    <el-dialog :title="configuredialog.title" v-model="configuredialog.visible" width="500px" append-to-body>
      <el-form ref="configureRef" :model="configureform" label-width="100px">
        <el-form-item label="应用秘钥" prop="appKey">
          <el-input v-model="configureform.appKey" placeholder="请输入应用秘钥" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="LoadingButton" type="primary" @click="configure_suer">确 定</el-button>
          <el-button @click="configure_cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 选择知识库对话框 -->
    <LibrarySelect ref="LibrarySelectRefs" @confirm="LibrarySelect_confirm"></LibrarySelect>
    <!-- 选择人员权限对话框 -->
    <ManageMembers ref="ManageMembersRefs" :onlyOne="true" :treeNodeId="appId" @onRefresh="ManageMembers_onRefresh"> </ManageMembers>
  </div>
</template>

<script setup lang="ts">
import {
  aiqaApiWikiAppsList,
  aiqaApiWikiAppsCreate,
  aiqaApiWikiAppsUpdate,
  aiqaApiWikiAppsDelete,
  aiqaWikiAppsAppIdAssignPermissions,
  expertUserApi
} from '@/api/know/expertBase/expertBaseApi';

import LibrarySelect from '@/views/know/expertBase/components/library-select.vue';
import ManageMembers from './components/manageMembers.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wiki_type } = toRefs<any>(proxy?.useDict('wiki_type'));

const openType = ref([
  { val: 1, label: '公开' },
  { val: 0, label: '不公开' }
]);
const dataList = ref<any>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const dialogFormRef = ref<ElFormInstance>();
const configureRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const configuredialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const LoadingButton = ref(false);
const configureform = ref({
  appKey: ''
});

const KeyId = ref(null);

const initFormData: any = {
  id: undefined,
  //   appName: undefined,
  appKey: undefined,
  description: undefined,
  //   wikiType: undefined,
  open: undefined,
  //   wikiIds: undefined,
  wikiNames: undefined
};
const data = reactive<any>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // appName: undefined,
    wikiNames: undefined,
    userName: undefined,
    params: {}
  },
  rules: {
    wikiNames: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
    open: [{ required: true, message: '是否公开不能为空', trigger: 'change' }],
    appKey: [{ required: true, message: '秘钥不能为空', trigger: 'blur' }]
    // wikiType: [{ required: true, message: '类型不能为空', trigger: 'blur' }]
  }
});

const isappKey = ref(false);

const { queryParams, form, rules } = toRefs(data);
const LibrarySelectRefs: any = ref(null);
const wikiList = ref([]); //创建的时候选择的知识库列表
const wikiListNames = ref([]); //编辑的时候回显的知识库列表

const ManageMembersRefs: any = ref(null);
const appId = ref(0);
/** 查询知识库配置11列表 */
const getList = async () => {
  loading.value = true;
  const res = await aiqaApiWikiAppsList(queryParams.value);
  dataList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  dialogFormRef.value?.resetFields();
  wikiList.value = [];
  wikiListNames.value = [];
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const Names = ref<Array<string | number>>([]);
/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item) => item.id);
  Names.value = selection.map((item) => item.wikiNames);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  isappKey.value = true;
  reset();
  dialog.visible = true;
  dialog.title = '添加知识库应用';
};

//配置
const configure = async (row?: any) => {
  KeyId.value = row.id;
  configureform.value.appKey = row.appKey;

  configuredialog.visible = true;
  configuredialog.title = '配置秘钥';
};

// 配置取消
const configure_cancel = () => {
  configureRef.value?.resetFields();
  configureform.value.appKey = '';
  KeyId.value = null;
  configuredialog.visible = false;
};

// 配置确定
const configure_suer = async () => {
  let oParam = {
    id: KeyId.value,
    appKey: configureform.value.appKey
  };

  await aiqaApiWikiAppsUpdate(oParam).then((res) => {
    LoadingButton.value = true;
    if (res.code == 200) {
      proxy?.$modal.msgSuccess('操作成功');
      configuredialog.visible = false;
      LoadingButton.value = false;
      getList();
    }
  });
};
/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset();
  const _id = row?.id || ids.value[0];
  // const res = await getKnowledgeConfig(_id);
  let wikiListNames = row.wikiNames ? row.wikiNames.split(',') : [];
  //   let wikiIds = row.wikiIds ? row.wikiIds.split(',') : [];
  //   wikiList.value = wikiIds.map((item) => {
  //     return {
  //       id: item,
  //       name: wikiListNames[wikiIds.indexOf(item)]
  //     };
  //   });
  isappKey.value = false;
  Object.assign(form.value, row);
  dialog.visible = true;
  dialog.title = '修改知识库应用';
};

/** 提交按钮 */
const submitForm = () => {
  dialogFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      //   form.value.wikiIds = wikiList.value.map((item) => item.id).join(',');
      //   form.value.wikiNames = wikiList.value.map((item) => item.name).join(',');
      if (form.value.id) {
        await aiqaApiWikiAppsUpdate(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await aiqaApiWikiAppsCreate(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      isappKey.value = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const _ids = row?.id ? [row.id] : ids.value;
  // const _Names = row?.wikiNames ? [row.wikiNames] : Names.value;

  await proxy?.$modal.confirm('是否确认删除知识库配置编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await aiqaApiWikiAppsDelete(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'aiqa/knowledgeConfig/export',
    {
      ...queryParams.value
    },
    `knowledgeConfig_${new Date().getTime()}.xlsx`
  );
};

//选择知识库--打开知识库列表
const handleSelectWiki = () => {
  LibrarySelectRefs.value.visibleDialog = true;
  LibrarySelectRefs.value.tableData = JSON.parse(JSON.stringify(wikiList.value));
};
// 选择知识库的Emit事件
const LibrarySelect_confirm = (val: any) => {
  wikiList.value = val;
};
//字典转换翻译
const getDictDataLabel = (value: any) => {
  return proxy?.selectDictLabel(wiki_type.value, value);
};
//打开权限配置
const openRoleDialog = (row: any) => {
  appId.value = row.id;
  nextTick(() => {
    ManageMembersRefs.value.addClick();
  });
};
// 人员权限对话框确定事件
const ManageMembers_onRefresh = (val) => {
  //   let userIds = [];
  let userId = null; // 存储单一的用户ID
  let userNames = [];
  let deptIds = [];
  let deptNames = [];
  val.forEach((item) => {
    if (item.type == 'user') {
      userId = item.typeId; // 只保存第一个用户的ID
      //   userIds.push(item.typeId);
      userNames.push(item.name);
    } else if (item.type == 'dept') {
      deptIds.push(item.typeId);
      deptNames.push(item.name);
    }
  });

  let oParam = {
    userId: userId,
    id: appId.value
  };
  expertUserApi(oParam)
    .then((res: any) => {
      proxy?.$modal.msgSuccess('操作成功');
      getList();
    })
    .catch((err: any) => {
      console.log(err);
      proxy?.$modal.msgError('操作失败');
    });
};
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.tag_class {
  margin-right: 5px;
  margin-bottom: 5px;
}

:deep(.el-form--inline .el-form-item__label) {
  width: 83px;
}
</style>
